const logger = require('../util/logger');

module.exports = (options) => {
  
  options = Object.assign({
    login: '/signIn',
    home: '/',
    ignoreUrls: [],
    validate: (ctx) => ctx.session.user !== undefined
  }, options);
  
  async function redirect(ctx, next) {
    let pathname = ctx.req._parsedUrl.pathname;
    const ignore = options.ignoreUrls.includes(pathname);
    const xhr = ctx.xhr || pathname.startsWith('/api/');
    
    if (ignore || pathname === options.login) {
      await next();
    } else if (xhr) {
      logger.info('The ajax request has no permission, need authorization.');
      ctx.status = 403;
      ctx.body = {
        success: false,
        errorMsg: '需要登录后操作'
      };
    } else {
      if (pathname === '/undefined') {
        pathname = '/';
      }
      ctx.redirect(options.login + '?origin=' + pathname);
    }
  }
  
  return async(ctx, next) => {
    if (!ctx.session) {
      throw new Error('No session found error');
    }
    
    let valid = options.validate(ctx);
    if (!valid) {
      await redirect(ctx, next);
    } else if (ctx.req._parsedUrl.pathname === options.login) {
      ctx.redirect(options.home);
    } else {
      await next();
    }
  }
};
